package com.ipan.kits.web;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import javax.activation.MimetypesFileTypeMap;

import com.ipan.kits.base.ExceptionUtil;
import com.ipan.kits.io.ResourceUtil;

/**
 * MIME工具
 * 
 * JDK7以下需要导入activation.jar
 * 
 * @author iPan
 * @version 2014-2-25
 */
public final class MimeUtil {
	private static MimetypesFileTypeMap MIME_TYPE_MAP = null;
	
	static {
//		InputStream fin = ClassLoaderUtils.getResourceAsStream("mime.types", MimeUtils.class);
		InputStream fin = null;
		try {
			fin = ResourceUtil.asStream(MimeUtil.class, "mime.types");
		} catch (IOException e1) {
			ExceptionUtil.unchecked(e1);
		}
		try {
			MIME_TYPE_MAP = new MimetypesFileTypeMap(fin);
		} finally {
			if (fin != null) {
				try {
					fin.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static String getContentType(File file) {
		return MIME_TYPE_MAP.getContentType(file);
	}
	
	public static String getContentType(String fileName) {
		return MIME_TYPE_MAP.getContentType(fileName);
	}
	
	public static void main(String[] args) {
		System.out.println(getContentType("Chrysanthemum.jpg"));
		System.out.println(getContentType(".jpg"));
		System.out.println(getContentType(".dot"));
	}

}
